package com.bc004346.travelus.dataAccess.asyncTasks;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;

import com.bc004346.travelus.dataAccess.TravelUsScreenScraper;
import com.bc004346.travelus.model.domain.Passenger;
import com.bc004346.travelus.model.domain.StringList;
import com.bc004346.travelus.model.interfaces.ISelectPassengerCallback;
import com.bc004346.travelus.utility.Utility;

import static com.bc004346.travelus.utility.Utility.log;

/**
 * Created by Renats on 4/1/2014.
 * Add passenger to PNR
 */
public class SelectPassengerTaskFragment extends Fragment {

    public static final String PAX = "pax";
    public static final String SELECTED_PAX = "selectedPax";
    private ISelectPassengerCallback mCallbacks;
    private TravelUsScreenScraper mTravelUS;
    private Passenger mPax;
    private StringList mSelectedPassengers;

    public static SelectPassengerTaskFragment newInstance(Passenger pax, StringList selectedPax) {
        SelectPassengerTaskFragment f = new SelectPassengerTaskFragment();
        Bundle args = new Bundle();
        args.putSerializable(PAX, pax);
        args.putSerializable(SELECTED_PAX, selectedPax);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mCallbacks = (ISelectPassengerCallback) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        mTravelUS = Utility.getInstance().getTravelUS();
        mPax = (Passenger) (getArguments() == null ? "" : getArguments().getSerializable(PAX));
        mSelectedPassengers = (StringList) (getArguments() == null ? null : getArguments().getSerializable(SELECTED_PAX));
        new SelectPassengerTask().execute();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    private class SelectPassengerTask extends AsyncTask<Void, Void, Passenger> {

        private Exception ex = null;

        @Override
        protected void onPostExecute(Passenger pax) {
            if (mCallbacks != null) {
                mCallbacks.onSelectPassengerPostExecute(pax, ex);
            }
        }

        @Override
        protected Passenger doInBackground(Void... params) {
            Passenger pax = mPax;
            try {
                return mTravelUS.selectPassenger(mPax, mSelectedPassengers);
            } catch (Exception e) {
                log(String.format("Exception: %s", e.toString()));
                ex = e;
            }
            return pax;
        }
    }
}
